import 'dart:convert';

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_reader/dao/check_data_manager.dart';
import 'package:flutter_reader/model/check/check_config_model.dart';
import 'package:flutter_reader/model/home/HotModel.dart';
import 'package:flutter_reader/pages/Login/login_nav_page.dart';
import 'package:flutter_reader/pages/home/recharge/protocol_dialog.dart';
import 'package:flutter_reader/pages/read_book/book_introduction.dart';
import 'package:flutter_reader/tools/color_loader.dart';
import 'package:flutter_reader/tools/rich_alert.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intervalprogressbar/intervalprogressbar.dart';
import 'package:liquid_progress_indicator/liquid_progress_indicator.dart';
import 'package:nice_button/nice_button.dart';
import 'package:shared_preferences/shared_preferences.dart';


class CheckPage extends StatefulWidget {
  CheckPage({Key key}) : super(key: key);

  @override
  _CheckPageState createState() {
    return _CheckPageState();
  }
}

class _CheckPageState extends State<CheckPage> {
  bool _isLoadingConfig = true;
  bool _isLoadingCoin = true;

  CheckConfigModel _configModel;
  CheckConfigData _checkConfigData;

  List<CheckConfigLists> _checkList;

  int coin = 0;
  int gift = 0;
  int next = 0;
  int current = 0;
  int nextNeed = 0;

  bool canCheck = false;
  bool todayCheck = false;


  //progress是反的
  var progressNow = 7;
  var now = DateTime.now();
  @override
  void initState() {
    loadConfig();
    // initPlatformState();
    super.initState();
    // LcfarmFlutterUmeng.onResume();
    // LcfarmFlutterUmeng.beginLogPageView('check');
  }

  @override
  void dispose() {
    super.dispose();
    // LcfarmFlutterUmeng.onPause();
    // LcfarmFlutterUmeng.endLogPageView('check');
  }

  ///集成极光推送
  String debugLable = 'Unknown';
  // final JPush jpush = new JPush();

  // Future<void> initPlatformState() async {
  //   String platformVersion;
  //   try {
  //     jpush.addEventHandler(
  //       onOpenNotification: (Map<String, dynamic> message) async {
  //         print('通知栏打开');
  //         print("flutter onOpenNotification: $message");
  //         print("${message["extras"]}");
  //         print("${message["extras"]["cn.jpush.android.EXTRA"]}");
  //         Map aa = json.decode(message["extras"]["cn.jpush.android.EXTRA"]);
  //         print("${aa["bookID"]}");
  //         Navigator.push(context, MaterialPageRoute(
  //             builder: (context) => BookInfoPage(bookId: aa["bookID"],channel: "1",)
  //         ));
  //       },
  //     );
  //   } on PlatformException {
  //     platformVersion = 'Failed to get platform version.';
  //   }
  // }

  loadConfig(){
    CheckDao.fetchCheckConfig().then((value){
      setState(() {
        coin = value.data.coin;
        gift = value.data.gift;
        current = value.data.daily.current;
        print(current);
        _checkList = value.data.daily.lists;
        next = value.data.daily.lists[current].coin;
        todayCheck = value.data.daily.today;
        nextNeed = value.data.daily.next;

        _isLoadingCoin = false;
        _isLoadingConfig = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("每日签到"),
      ),
      body: _isLoadingConfig ? Container(
        width: ScreenUtil.screenWidth,
        height: ScreenUtil.screenHeight,
        child: Center(
          child: Container(
            padding: EdgeInsets.only(top: ScreenUtil().setHeight(1000)),
            child: Column(
              children: <Widget>[
                ColorLoader(
                  color1: Colors.redAccent,
                  color2: Colors.green,
                  color3: Colors.amber,
                ),
                Container(
                  margin: EdgeInsets.only(top: ScreenUtil().setHeight(60)),
                  child: Text(
                      '正在为您生成签到页...'
                  ),
                )
              ],
            ),
          ),
        ),
      ) :
      Container(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    colorFilter: new ColorFilter.mode(
                        Colors.black.withOpacity(1), BlendMode.dstATop),
                    image: AssetImage('images/checkBg.png'),
                    fit: BoxFit.cover,
                  ),
                ),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: Container(
                        child: Center(
                          child: Text(
                            "可用书币\n      ${coin.toString()}",
                            style: TextStyle(
                              fontSize: ScreenUtil().setSp(50),
                              color: Colors.white
                            ),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child:InkWell(
                        onTap: _pressCheckIn,
                        child:  Container(
                          child: Center(
                            child: Text(todayCheck == true ? "${nextNeed.toString()}币补签" : "今日签到",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenUtil().setSp(50)
                              ),),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: Container(
                        child: Center(
                          child: Text(
                            "可用书券\n      ${gift.toString()}",
                            style: TextStyle(
                                fontSize: ScreenUtil().setSp(50),
                                color: Colors.white
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                )
              ),
            ),
            _ruleRow(),
            Expanded(
              flex: 3,
              child: Container(
                child: Column(
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: _iconRow(1),
                    ),
                    Expanded(
                      flex: 1,
                      child: _iconRow(7),
                    ),
                    Expanded(
                      flex: 1,
                      child: _iconRow(13),
                    ),
                    Expanded(
                      flex: 1,
                      child: _iconRow(19),
                    ),
                    Expanded(
                      flex: 1,
                      child: _iconRow(25),
                    ),
                    Expanded(
                      flex: 1,
                      child: _lastIconRow(31),
                    )
                  ],
                )
              ),
            )
          ],
        ),
      )
    );
  }

  _ruleRow(){
    return Container(
      width: ScreenUtil().setWidth(1125),
      height: ScreenUtil().setHeight(150),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: ScreenUtil().setWidth(50)),
            width: ScreenUtil().setWidth(100),
            height: ScreenUtil().setHeight(150),
            child: FittedBox(
              child: Text(
                "签到",
                style: TextStyle(
                  color: Colors.redAccent
                ),
              ),
            )
          ),
          InkWell(
            onTap: _pressProblem,
            child: Container(
                margin: EdgeInsets.only(right: ScreenUtil().setWidth(50)),
                width: ScreenUtil().setWidth(200),
                height: ScreenUtil().setHeight(150),
                child: FittedBox(
                  child: Text(
                    "签到规则 >",
                  ),
                )
            ),
          )
        ],
      ),
    );
  }

  _iconRow(int i){
    return Row(
      children: <Widget>[
        Expanded(
          flex: i,
          child: _littleIcon(i),
        ),
        Expanded(
          flex: i,
          child: _littleIcon(i+1),
        ),
        Expanded(
          flex: i,
          child: _littleIcon(i+2),
        ),
        Expanded(
          flex: i,
          child: _littleIcon(i+3),
        ),
        Expanded(
          flex: i,
          child: _littleIcon(i+4),
        ),
        Expanded(
          flex: i,
          child: _littleIcon(i+5),
        ),
      ],
    );
  }
  
  _lastIconRow(int i){
    return Row(
      children: <Widget>[
        Expanded(
          flex: i,
          child: _littleIcon(i),
        ),
        Expanded(
          flex: i,
          child: Container(

          ),
        ),
        Expanded(
          flex: i,
          child: Container(

          ),
        ),
        Expanded(
          flex: i,
          child: Container(

          ),
        ),
        Expanded(
          flex: i,
          child: Container(

          ),
        ),
        Expanded(
          flex: i,
          child: Container(

          ),
        ),
      ],
    );
  }

  _littleIcon(int day){
    return Container(
      child: day <= current ?
      Container(
        padding: EdgeInsets.only(bottom: ScreenUtil().setHeight(50)),
        child: Image(
          width: ScreenUtil().setWidth(100),
          image: AssetImage("images/haveCheck.png"),
        ),
      ) :
      Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              width: ScreenUtil().setWidth(100),
              child: Stack(
                children: <Widget>[
                  Image(
                    width: ScreenUtil().setWidth(100),
                    image: AssetImage('images/checkCoin.png'),
                  ),
                  Container(
                    height: ScreenUtil().setWidth(100),
                    child: Center(
                      child: Text(
                          "${_checkList[day - 1].coin}"
                      ),
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(50)),
              child: Text('${day.toString()} 天'),
            )
          ],
        ),
      ),
    );
  }

  _pressCheckIn() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    if(sharedPreferences.getString("login")=="true")
      {
        CheckDao.getToCheck().then((value){
          setState(() {
            if(value.success == true){
              _updateCoin();
              current = current + 1;
              next = _checkList[current - 1].coin;
              showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return RichAlertDialog( //uses the custom alert dialog
                      alertTitle: richTitle("签到成功"),
                      alertSubtitle: richSubtitle("恭喜赢得书币"),
                      alertType: RichAlertType.SUCCESS,
                    );
                  }
              );
            }
            else{
              showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return RichAlertDialog( //uses the custom alert dialog
                      alertTitle: richTitle("签到失败"),
                      alertSubtitle: richSubtitle("书币不足"),
                      alertType: RichAlertType.WARNING,
                    );
                  }
              );
            }
          });
        });
      }
    else
      {
        print("先登录");
        Navigator.push(context, MaterialPageRoute(
            builder: (context) => LoginNavPage()
        )).then((value){
          loadConfig();
        });
      }
  }


  _updateCoin(){
    _isLoadingCoin = true;
    CheckDao.fetchCheckConfig().then((value){
      setState(() {
        coin = value.data.coin;
        gift = value.data.gift;
        todayCheck = value.data.daily.today;
        nextNeed = value.data.daily.next;
        _isLoadingCoin = false;
      });
    });
  }

  _pressProblem(){
    showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context){
          return ProtocolDialog(
            title: '签到规则说明',
            dialogText: '(一) 新用户登录豪华礼包\n\n1、新用户每日首次登录书城，可获得新用户签到福利，共计7次。\n\n(二) 每日签到\n\n1、签到周期为自然月，每个自然月总计可签到次数为当月实际天数,每月1号清零。\n2、可补签，每个自然月补签不限次数。补签消耗书币详情：第1次消耗5书币，第二次消耗10书币，第三次消耗15书币，第四次消耗20书币，第五次及以上消耗25书币',
          );
        }
    );
  }

  _changeToChinese(int weekdate) {
    String dateCN;
    switch (weekdate) {
      case 1:
        {
          dateCN = '一';
        }
        break;
      case 2:
        {
          dateCN = '二';
        }
        break;
      case 3:
        {
          dateCN = '三';
        }
        break;
      case 4:
        {
          dateCN = '四';
        }
        break;
      case 5:
        {
          dateCN = '五';
        }
        break;
      case 6:
        {
          dateCN = '六';
        }
        break;
      case 7:
        {
          dateCN = '日';
        }
        break;
    }
    return dateCN;
  }
}